from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from web.models import Notice, NoticeImage, Users
from django.forms.models import model_to_dict
from django import forms
from web.apis import tools
from datetime import datetime

# 公告表单
class NoticeForm(forms.ModelForm):
    class Meta:
        model = Notice
        fields = ['notice_title', 'notice_content', 'notice_publisher']

# 公告图片表单
class NoticeImageForm(forms.ModelForm):
    class Meta:
        model = NoticeImage
        fields = ['notice', 'image']

# 创建公告
@csrf_exempt
def create_notice(request):
    if request.method == 'POST':
        form = NoticeForm(request.POST)
        if form.is_valid():
            try:
                form.save()
                notice = form.instance
                notice_dict = model_to_dict(notice)
                notice_dict['notice_publisher'] = notice.notice_publisher.username
                notice_dict['create_time'] = notice.create_time.strftime('%Y-%m-%d %H:%M:%S')
                notice_dict['update_time'] = notice.update_time.strftime('%Y-%m-%d %H:%M:%S')
                return JsonResponse(tools.ReturnData(code=200, msg="公告创建成功", data=notice_dict))
            except Exception as e:
                return JsonResponse(tools.ReturnData(code=400, msg=f'保存公告失败: {str(e)}'))
        else:
            error_msg = tools.get_first_error(form)
            return JsonResponse(tools.ReturnData(code=400, msg=f'{error_msg}'))
    else:
        return JsonResponse(tools.ReturnData(code=405, msg="请使用POST方法"))

# 获取公告列表
@csrf_exempt
def get_notice_list(request):
    if request.method == 'GET':
        try:
            notices = Notice.objects.all().order_by('-create_time')
            notice_list = []
            for n in notices:
                n_dict = model_to_dict(n)
                n_dict['notice_publisher'] = n.notice_publisher.username if n.notice_publisher else ''
                n_dict['create_time'] = n.create_time.strftime('%Y-%m-%d %H:%M:%S')
                n_dict['update_time'] = n.update_time.strftime('%Y-%m-%d %H:%M:%S')
                notice_list.append(n_dict)
            return JsonResponse(tools.ReturnData(code=200, msg='获取公告列表成功', data=notice_list))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'获取公告列表失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=405, msg='请使用GET方法'))

# 获取单个公告
@csrf_exempt
def get_notice(request, notice_id):
    if request.method == 'GET':
        try:
            n = Notice.objects.filter(notice_id=notice_id).first()
            if not n:
                return JsonResponse(tools.ReturnData(code=400, msg='公告不存在'))
            n_dict = model_to_dict(n)
            n_dict['notice_publisher'] = n.notice_publisher.username if n.notice_publisher else ''
            n_dict['create_time'] = n.create_time.strftime('%Y-%m-%d %H:%M:%S')
            n_dict['notice_image'] = []
            for i in NoticeImage.objects.filter(notice=n.notice_id):
                data = model_to_dict(i)
                data['image'] = i.image.url
                data['create_time'] = i.create_time.strftime('%Y-%m-%d %H:%M:%S')
                data['update_time'] = i.update_time.strftime('%Y-%m-%d %H:%M:%S')
                n_dict['notice_image'].append(data)
            n_dict['update_time'] = n.update_time.strftime('%Y-%m-%d %H:%M:%S')
            return JsonResponse(tools.ReturnData(code=200, msg='获取公告成功', data=n_dict))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'获取公告失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=405, msg='请使用GET方法'))

# 更新公告
@csrf_exempt
def update_notice(request, notice_id):
    if request.method == 'POST':
        try:
            n = Notice.objects.filter(notice_id=notice_id).first()
            if not n:
                return JsonResponse(tools.ReturnData(code=400, msg='公告不存在'))
            n.notice_title = request.POST.get('notice_title', n.notice_title)
            n.notice_content = request.POST.get('notice_content', n.notice_content)
            # notice_publisher 通常不更新
            n.update_time = datetime.now()
            n.save()
            n_dict = model_to_dict(n)
            n_dict['notice_publisher'] = n.notice_publisher.username if n.notice_publisher else ''
            n_dict['create_time'] = n.create_time.strftime('%Y-%m-%d %H:%M:%S')
            n_dict['update_time'] = n.update_time.strftime('%Y-%m-%d %H:%M:%S')
            return JsonResponse(tools.ReturnData(code=200, msg='更新公告成功', data=n_dict))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'更新公告失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=405, msg='请使用POST方法'))

# 删除公告
@csrf_exempt
def delete_notice(request, notice_id):
    if request.method == 'DELETE':
        try:
            n = Notice.objects.filter(notice_id=notice_id).first()
            if not n:
                return JsonResponse(tools.ReturnData(code=400, msg='公告不存在'))
            n.delete()
            return JsonResponse(tools.ReturnData(code=200, msg='删除公告成功'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'删除公告失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用DELETE方法'))

# 上传公告图片
@csrf_exempt
def upload_notice_image(request, notice_id):
    if request.method == 'POST':
        try:
            notice = Notice.objects.filter(notice_id=notice_id).first()
            if not notice:
                return JsonResponse(tools.ReturnData(code=400, msg='公告不存在'))
            if 'image' not in request.FILES:
                return JsonResponse(tools.ReturnData(code=400, msg='请上传图片'))
            image_file = request.FILES['image']
            notice_image = NoticeImage.objects.create(notice=notice, image=image_file)
            image_dict = model_to_dict(notice_image)
            image_dict['image'] = notice_image.image.url
            image_dict['create_time'] = notice_image.create_time.strftime('%Y-%m-%d %H:%M:%S')
            image_dict['update_time'] = notice_image.update_time.strftime('%Y-%m-%d %H:%M:%S')
            return JsonResponse(tools.ReturnData(code=200, msg='上传公告图片成功', data=image_dict))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'上传公告图片失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用POST方法'))

# 删除公告图片
@csrf_exempt
def delete_notice_image(request, image_id):
    if request.method == 'DELETE':
        try:
            image = NoticeImage.objects.filter(id=image_id).first()
            if not image:
                return JsonResponse(tools.ReturnData(code=400, msg='公告图片不存在'))
            image.delete()
            return JsonResponse(tools.ReturnData(code=200, msg='删除公告图片成功'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'删除公告图片失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用DELETE方法'))

